package com.ktjiaoyu.ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();
    @Override
    public List<Category> findAll() throws SQLException {
        return categoryDao.findAll();
    }

    @Override
    public List<Category> getTree() throws SQLException {
        List<Category> all = categoryDao.findAll();

        return buildTree(all, "0");
    }

    private List<Category> buildTree(List<Category>  all , String parent_id){
        List<Category> list = new ArrayList<>();
        for (Category category : all){
            if(category.getParent_id() != null && category.getParent_id().equals(parent_id)){
                // 把当前分类的子分类全部存放到children中
                category.setChildren(buildTree(all, category.getId()));
                list.add(category);
            }
        }
        return list;
    }

    @Override
    public boolean saveOrUpdate(Category category) throws SQLException {
            if(category.getId() == null){
                return categoryDao.insert(category) > 0;
            }else{
                return categoryDao.update(category) > 0;
            }
    }

    @Override
    public boolean removeById(Long id) throws SQLException {
        return categoryDao.delete(id) > 0;
    }
}
